package com.heye.imheye.event;

import com.heye.imheye.entity.Message;
import com.heye.imheye.ws.WsContainer;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@RequiredArgsConstructor
public class EventPublisher {

    private final WsContainer wsContainer;
    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    public void publish(Message message) {
        Integer toType = message.getToType();
        Set<Long> receivers = getReceivers();
        executor.execute(() -> {
            receivers.forEach(userId -> {
                WebSocketSession session = wsContainer.getSessionByUserId(userId);
                try {
                    session.sendMessage(new TextMessage("有人给你发了消息"));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        });
    }

    private Set<Long> getReceivers() {
        return wsContainer.getSessions().keySet();
    }
}
